﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        MusicEntities musicDb = new MusicEntities();
               
        public ActionResult Index()
        {
            var albums = musicDb.Albums.ToList(); 
            return View(albums);
        }

        public ActionResult Create()
        {
            ViewBag.Genres = musicDb.Genres.OrderBy(g => g.Name).ToList();
            var al = new Album();
            return View(al);
        }

        [HttpPost]
        public ActionResult Create(Album al)
        {

            if (ModelState.IsValid)
            {
                musicDb.Albums.Add(al);
                musicDb.SaveChanges();
                return RedirectToAction("index","store");
            }
            ViewBag.Genres = musicDb.Genres.OrderBy(g => g.Name).ToList();
            return View(al);
           
        }

        public ActionResult Edit(int id)
        {
            ViewBag.Genres = musicDb.Genres.OrderBy(g => g.Name).ToList();
            Album al = musicDb.Albums.Single(a => a.AlbumId == id);
            return View(al);

        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id,FormCollection fc) 
        {
            Album al = musicDb.Albums.Find(id);

            if (TryUpdateModel(al))
            {
                musicDb.SaveChanges();
                return RedirectToAction("Index", "Store");
            }
            else 
            {
                ViewBag.Genres = musicDb.Genres.OrderBy(a => a.Name).ToList();
                return View(al);
           }
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var album = musicDb.Albums.Find(id);
            musicDb.Albums.Remove(album);
            musicDb.SaveChanges();
            return JavaScript("alert('Person Deleted.')");
        
        }

        //this was on a example. [JsonOnly]
        [HttpPost]
        public ActionResult JsonTest(CordobianClass req) {
            return Json(req);
        }

        public ActionResult JsonTest() {
           return View();
        }

        public class CordobianClass {
            public int Id;
            public string Name;
      
        }
    }
}
